package ru.fivestarter.view.authorisation;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.Random;

import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;


import com.octo.captcha.service.image.ImageCaptchaService;

public class RegisterController{
	public static final String CAPTCHA_ID = "EmForge";
	private ImageCaptchaService imageCaptchaService;
	private String secureText;
	private int captchaWidth=200;
	private int captchaHeight=100;

	public RegisterController() {
		// TODO Auto-generated constructor stub
	}

	public ImageCaptchaService getImageCaptchaService() {
		return imageCaptchaService;
	}

	public void setImageCaptchaService(ImageCaptchaService imageCaptchaService) {
		this.imageCaptchaService = imageCaptchaService;
	}

	public String getSecureText() {
		return secureText;
	}

	public void setSecureText(String secureText) {
		this.secureText = secureText;
	}

	public int getCaptchaWidth() {
		return captchaWidth;
	}

	public void setCaptchaWidth(int captchaWidth) {
		this.captchaWidth = captchaWidth;
	}
	
	public int getCaptchaHeight() {
		return captchaHeight;
	}

	public void setCaptchaHeight(int captchaHeight) {
		this.captchaHeight = captchaHeight;
	}

	public static String getCaptchaId() {
		return CAPTCHA_ID;
	}
	protected BufferedImage generateCaptcha(){
		
		ImageCaptchaService imageCaptchaService=(ImageCaptchaService) FacesContext.getCurrentInstance().getApplication().getExpressionFactory().createValueExpression(FacesContext.getCurrentInstance().getELContext(), "#{imageCaptchaService}", ImageCaptchaService.class).getValue(FacesContext.getCurrentInstance().getELContext());
		try{
			return imageCaptchaService.getImageChallengeForID(CAPTCHA_ID);
		}catch (Exception e) {
			System.out.println(e);
            return null;
			// TODO: handle exception
		}
	}
	public void paintCaptcha(OutputStream out, Object obj) {
	        BufferedImage img = generateCaptcha();
	        Graphics2D g2d = img.createGraphics();
	        try {
	            g2d.setClip(0,0,img.getWidth(), img.getHeight());
	            g2d.drawImage(img, 0,0, null);
	            ImageIO.write(img, "png", out);
	        } catch (Exception e) {
	        	System.out.println(e);
	        }
	}
	/** Generates Random Text for displaying on the image */
    public String getRandomString() {
        String str=new  String("QAa0bcLdUK2eHfJgTP8XhiFj61DOklNm9nBoI5pGqYVrs3CtSuMZvwWx4yE7zR");
         StringBuffer sb=new StringBuffer();
         Random r = new Random();
         int te=0;
         for(int i=1;i<=6;i++){
             te=r.nextInt(62);
             sb.append(str.charAt(te));
         }
        
         return sb.toString();
    } 


}
